#!/usr/bin/env bash
# 说明：二进制安装 mysql

###

Downloads_bin_file_address="https://mirrors.ustc.edu.cn/mysql-ftp/Downloads/MySQL-5.7/mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz"
install_dir="/data"
mysql_bin_file="mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz"

# 下载 mysql 二进制文件
[ $(whereis wget | wc -l) -ne 1 ] && yum -y -q install wget
wget ${Downloads_bin_file_address}

# 创建安装目录
[ ! -d ${install_dir} ] && mkdir ${install_dir}

# 解压二进制到指定目录
tar -zxf ${mysql_bin_file} -C ${install_dir}/

# 修改目录名字，便于使用
mv ${install_dir}/mysql-5.7.35-linux-glibc2.12-x86_64 ${install_dir}/mysql5.7.35

# 创建配置目录和数据目录
mkdir -p ${install_dir}/mysql5.7.35/{data,conf}

# 生成配置文件
cat > ${install_dir}/mysql5.7.35/conf/my.cnf << EOF
[client] 
default-character-set  = utf8mb4

[mysql]
port                   = 3306
socket                 = ${install_dir}/mysql5.7.35/data/mysql.sock
default-character-set  = utf8mb4

[mysqld]
port                   = 3306
default_storage_engine = InnoDB
basedir                = ${install_dir}/mysql5.7.35
datadir                = ${install_dir}/mysql5.7.35/data
socket                 = ${install_dir}/mysql5.7.35/data/mysql.sock
character-set-client-handshake = FALSE
character-set-server   = utf8mb4
collation-server       = utf8mb4_unicode_ci
init_connect           = 'SET NAMES utf8mb4'
max_connections        = 2000
max_allowed_packet     = 128M
innodb_file_per_table  = 1
tmp_table_size         = 134217728
max_heap_table_size    = 134217728
lower_case_table_names = 1

log-bin                = mysql-bin
max_binlog_size        = 1024M
expire_logs_days       = 1
log_slave_updates      = 1
server-id              = 1

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

EOF

# 创建运行账号
useradd mysql

# 授权相关目录权限
chown -R mysql.mysql ${install_dir}

# 写入环境变量
cat >> /home/mysql/.bashrc << EOF
export PATH=${install_dir}/mysql5.7.35/bin:\$PATH

EOF

# 环境变量生效
source /home/mysql/.bashrc

# 软连接sock文件
ln -s ${install_dir}/mysql5.7.35/data/mysql.sock /tmp/mysql.sock

# 初始化 mysql
mysqld --defaults-file=${install_dir}/mysql5.7.35/conf/my.cnf --user=mysql --initialize | grep "password"

# 启动mysql
${install_dir}/mysql5.7.35/bin/mysqld_safe --defaults-file=${install_dir}/mysql5.7.35/conf/my.cnf --user=mysql &

